package com.tool.serialize;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 酒徒
 * @Version 1.0
 * @data 2024/1/23 17:25
 * Jackson库 广泛，集成
 * Fastjson库 高性能
 */
public class TestJSON {
    public static void main(String[] args) throws Exception {
        testJackson();
        testFastjson();
    }

    /**
     * 使用JacksonObjectMapper完成序列化与反序列化
     *
     * @throws Exception
     */
    private static void testJackson() throws Exception {
        System.out.println("未序列化");
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        System.out.println(localDateTime);
        System.out.println(localDate);
        System.out.println(localTime);

        System.out.println("序列化");
        ObjectMapper json = new JacksonObjectMapper();
        String localDateTimeRes = json.writeValueAsString(localDateTime);
        String localDateRes = json.writeValueAsString(localDate);
        String localTimeRes = json.writeValueAsString(localTime);
        System.out.println(localDateTimeRes);
        System.out.println(localDateRes);
        System.out.println(localTimeRes);

        System.out.println("反序列化");
        ObjectMapper java = new JacksonObjectMapper();
        LocalDateTime localDateTimeR = java.readValue(localDateTimeRes, LocalDateTime.class);
        LocalDate localDateR = java.readValue(localDateRes, LocalDate.class);
        LocalTime localTimeR = java.readValue(localTimeRes, LocalTime.class);
        System.out.println(localDateTimeR);
        System.out.println(localDateR);
        System.out.println(localTimeR);
    }

    /**
     * Jackson库的序列化与反序列化
     */
    private static void testFastjson() {
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("初始数据" + localDateTime);
        String json = JSON.toJSONString(localDateTime, SerializerFeature.WriteDateUseDateFormat);
        System.out.println("序列化：" + json);
        LocalDateTime time = JSON.parseObject(json, LocalDateTime.class);
        System.out.println("反序列化：" + time);

        SerializeConfig config = new SerializeConfig();
        config.put(LocalDateTime.class, (serializer, object, fieldName, fieldType, features) -> {
            LocalDateTime localDateTime1 = (LocalDateTime) object;
            String formattedDateTime = localDateTime1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            serializer.write(formattedDateTime);
        });
        json = JSON.toJSONString(localDateTime, config, SerializerFeature.WriteDateUseDateFormat);
        System.out.println("自定义序列化: " + json);
    }
}
